package com.heatingcharge.service.base.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.BeanValidator;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.entity.base.HeatYear;
import com.heatingcharge.mapper.base.HeatYearMapper;
import com.heatingcharge.param.HeatYearParam;
import com.heatingcharge.service.base.IHeatYearService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-10-13
 */
@Service
public class HeatYearServiceImpl extends ServiceImpl<HeatYearMapper, HeatYear> implements IHeatYearService {

    @Override
    public Integer save(HeatYearParam heatYearParam) {
        //校验字段合法性
        BeanValidator.check(heatYearParam);
        //检验年度是否已经存在
        if (checkExist(heatYearParam.getYearName(),null)){
            //年度已经存在
            throw new BaseException(ResponseCodeEnum.HEATYEAR_EXIST.getMessage(),ResponseCodeEnum.HEATYEAR_EXIST.getCode());
        }
        HeatYear heatYear=HeatYear.builder()
                .yearName(heatYearParam.getYearName())
                .chargeStart(heatYearParam.getChargeStart())
                .chargeEnd(heatYearParam.getChargeEnd())
                .heatStart(heatYearParam.getHeatStart())
                .heatEnd(heatYearParam.getHeatEnd())
                .build();
        return baseMapper.insert(heatYear);
    }

    private boolean checkExist(String yearName, Integer id) {
        QueryWrapper<HeatYear> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("year_name",yearName);
        if (id!=null){
            queryWrapper.ne("id",id);
        }
        return baseMapper.selectOne(queryWrapper) !=null;
    }

    @Override
    public Integer update(HeatYearParam heatYearParam) {
        //校验字段合法性
        BeanValidator.check(heatYearParam);
        //检验年度是否已经存在
        if (checkExist(heatYearParam.getYearName(),heatYearParam.getId())){
            //年度已经存在
            throw new BaseException(ResponseCodeEnum.HEATYEAR_EXIST.getMessage(),ResponseCodeEnum.HEATYEAR_EXIST.getCode());
        }
        HeatYear before=baseMapper.selectById(heatYearParam.getId());
        //待更新的不存在
        if (ObjectUtil.isNull(before)){
            throw new BaseException(ResponseCodeEnum.HEATYEAR_NON_EXIST.getMessage(),ResponseCodeEnum.HEATYEAR_NON_EXIST.getCode());
        }
        HeatYear after =new HeatYear();
        BeanUtils.copyProperties(heatYearParam,after);
        return baseMapper.updateById(after);
    }

    @Override
    public Integer delete(HeatYearParam heatYearParam) {
        return baseMapper.deleteById(heatYearParam.getId());
    }
}
